#This is a sample script to extract all MPTs from a treefile output by TNT and then calculate node-to-root distances
#Script received by Robert J. Asher, Dept Zoology, University of Cambridge and then adapted for use in this thesis
#Please do not distribute without permission from Robert J. Asher

#needs these libraries to run
library(data.table) #enable library with fread command
library(phangorn)
library(distory)
library(phyloch)

#extract each MPT not consensus from TNT output
prefix<-"rtx"
suffix<-".out"
suffix2<-"\\.out"
outfile<-"TNTtrees.nex"
study<-"Glires" #add name of matrix/paper/etc here
data<-"real" #real/random-etc here 
write(paste("#nexus","[",study," ",data,"]"), file = outfile, append = T)
write(paste("begin trees;"), file = outfile, append = T)
metadata<-"nodeHeight-meta.txt"
write(paste("study","data","subject","template","rep","topo",sep = "&"), file = metadata, append = F)
#put into z filenames with pattern
z<-list.files(path=".",pattern=suffix,recursive=F)
for (i in 1:length(z) ){
  #extract subject & template from filename
  filename<-gsub(suffix2,"",z[i])
  filename<-gsub(prefix,"",filename) #edit this & next line to clean up file names to be read as subect & template
  filename<-gsub("randMult","",filename)
  template<-gsub(".*?\\_","",filename)
  subject<-gsub("\\_.*","",filename)
  #count lines in textfile to be able to select variable number of newick trees across many files
  lines<-length(count.fields(file=z[i],blank.lines.skip = F)) 
  #put into variable strict lines from 1st occurrence of "skip =" until total number of lines -7 (in order to get all MPTs, skipping the last newick topology which is consensus)
  MPTs <- fread(z[i],skip = "tree tnt",nrows=lines-7, sep = "",header=F) #reads into variable tree one row of text from file z[i] starting at lineStrict 
  #since replicates are on every other line from 1, and topologies from 2, extract both and paste into separate columns in one data frame 
  reps<-seq(from=1,to=max(length(MPTs$V1)),by=2) 
  reps<-data.frame(c(MPTs[reps,]))
  reps$V1<-gsub("tree ","",reps$V1)
  reps$V1<-gsub("[&U]","",fixed = T,reps$V1)
  topos<-seq(from=2,to=max(length(MPTs$V1)),by=2)
  topos<-data.frame(c(MPTs[topos,]))
  #combine into one dataframe
  MPTs<-cbind(reps,topos)
  colnames(MPTs)<-c("reps","topos")
  #write all MPTs into one textfile for all MPTs of each subject-template combination (so append = T)
  write(paste("tree ",subject,template,"_",MPTs$reps,MPTs$topos,sep = ""), file = outfile, append = T)
  write(paste(study,data,subject,template,MPTs$reps,MPTs$topos,sep = "&"), file = metadata, append = T)
}

#finish nexus format with "end"
write(paste("end;"), file = outfile, append = T)


#Script by Seraina Klopfstein, Naturhistorisches Museum Basel CH to return the height of a node (=root-node distance) or tip either in sum of branch lengths or in number of nodes. 
node.height <- function (tree, nodeIndex, dist.type = "nodes") {
  nodeHeight <- 0.0
  parent <- tree$edge[,1]
  child <- tree$edge[,2]
  while (!is.na(match(nodeIndex, child))) {  #while going down the tree towards the root
    if (dist.type == "branch.lengths"){
      nodeHeight <- nodeHeight+tree$edge.length[which(parent == nodeIndex)[1]]
    }  else if (dist.type == "nodes") {
      nodeHeight <- nodeHeight +1
    } else {
      warning(paste("Error in function 'node.height': unknown setting for distance type - '", dist.type, "' encountered. Valid settings are 'branch.lengths' and 'nodes'. Aborting...", sep = ""))
      return(NA)
    }
    nodeIndex <- parent[which(child == nodeIndex)[1]]
  }
  return(nodeHeight)
}

#script to calculate root-node distance for each MPT, using function and nexus formatted trees written above
nhMeta<-read.table("nodeHeight-meta.txt",sep="&",header = T) #metadata for nexus treefile here, "nodeHeight-meta.txt"
trees<-read.nexus("TNTtrees.nex") #all TNT MPTs formatted for nexus above, "TNTtrees.nex"
nodeDist<-"subDist.csv"
write(paste("study","data","subject","template","rep","nodeDist",sep = ","), file = nodeDist, append = F)
z <- length(trees)
for (i in 1:z){
  tree <- trees[[i]]
  node.index <- which(tree$tip.label == nhMeta$subject[i])
  nh<-node.height(tree, nodeIndex = node.index, dist.type = "nodes")
  write(paste(study,data,nhMeta$subject[i], nhMeta$template[i], nhMeta$rep[i],nh, sep = ","), file = nodeDist, append = T)
}  


ND<-read.csv("subDist.csv",header = T) #this should be "nodeDist.csv" file with stats for every subject-template combination
dt<-data.table(ND)
dt <- dt[, nodeDist:=as.numeric(nodeDist)]
nodeDist<-dt[, list(nodeDist.mean=sapply(.SD,mean), nodeDist.median=sapply(.SD, median), nodeDist.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
       by="subject", .SDcols=c("nodeDist")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)
nodeDist<-nodeDist[order(nodeDist$subject),]

##save this to csv and then subtract node distances to those counted manually from wellcorr.nwk
write.csv(nodeDist, "subject_nodeDist.csv", row.names=FALSE)


#calculate average node-to-root distance of subect taxa in reference topologies

wellcorrDist<-"wellcorrDist.csv" 
wellcor<- read.tree("wellcorr.nwk") #trees should all be bifurcating to compare with artex root-node distances
for (x in 1:length(wellcor)) {
  reftree <-wellcor[[x]] 
  treename <- attr(wellcor[x],"names") #assumes that treefile has informative names for each tree
  for (i in 1:length(reftree$tip.label)){
    node.index <- which(reftree$tip.label == reftree$tip.label[i])
    nh<-node.height(reftree, nodeIndex = node.index, dist.type = "nodes")
    write(paste(reftree$tip.label[i],treename,"wellcor",nh,sep = ","),file = wellcorrDist,append = T)
  }
}


#calculate average node-to-root distance of artifical fossil taxa in MPTs

ND<-read.csv("subDist.csv",header = T) #this should be "nodeDist.csv" file with stats for every subject-template combination
dt<-data.table(ND)
dt <- dt[, nodeDist:=as.numeric(nodeDist)]
nodeDist<-dt[, list(nodeDist.mean=sapply(.SD,mean), nodeDist.median=sapply(.SD, median), nodeDist.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
       by="template", .SDcols=c("nodeDist")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)
   
	   
#load & add metadata
meta<-read.csv("rtxMeta.csv",header = T)
#make sure that templates correspond exactly in row order before combining columns 

nodeDist<-nodeDist[order(nodeDist$template),]


#combine columns
rootnode<-cbind(meta,nodeDist)
#check that template columns in rtx correspond and then delete extraneous column
rootnode[,8]<-NULL #REMEMBER to check if the column you want to delete is "8"
write.csv(rootnode,file = "templates_nodeDists.csv",row.names = F)

